package com.example.service.user.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.RemoteJudgeService;
import com.example.domain.UserExeResult;
import com.example.domain.dto.JudgeSubmitDTO;
import com.example.domain.question.Question;
import com.example.domain.question.QuestionCase;
import com.example.domain.question.es.QuestionES;
import com.example.domain.user.UserSubmit;
import com.example.domain.user.dto.UserSubmitDTO;
import com.example.domain.vo.UserQuestionResultVO;
import com.example.elasticsearch.QuestionRepository;
import com.example.mapper.question.QuestionMapper;
import com.example.mapper.user.UserSubmitMapper;
import com.example.rabbitmq.JudgeProducer;
import com.example.security.exception.ServiceImplException;
import com.example.service.user.IUserQuestionService;
import oj.common.core.contants.JwtConstants;
import oj.common.core.domain.Result;
import oj.common.core.enums.CodeRunStatus;
import oj.common.core.enums.ProgramType;
import oj.common.core.enums.QuestionResType;
import oj.common.core.enums.ResultCode;
import oj.common.core.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceImplException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    //如果判题成功的话，会给前端一个提示
    //这时候前端会不断的想后端发起请求，查询后端这个结果，进行展示，前端实现一个定时任务
    @Override
    public boolean rabbitmqSubmit(UserSubmitDTO userbmitDTO) {
        Integer programType = userbmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userbmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceImplException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID, Long.class);
        //这个时候去数据库中查询
        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        //这里不能这样写，其实这样写也没有问题，因为如果有的话，数据就存在了，没有的话就在判题中。
        //会把相应的结果返回给前端。
        UserSubmit userSubmit = userSubmitMapper.selectOne(new LambdaQueryWrapper<UserSubmit>()
                .eq(UserSubmit::getUserId, userId)
                .eq(UserSubmit::getQuestionId, questionId)
                .isNull(examId == null, UserSubmit::getExamId)
                .eq(examId != null, UserSubmit::getExamId, examId));
        if (userSubmit == null) {
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
            userQuestionResultVO.setExeMessage(CodeRunStatus.RUNNING.getMsg());
        } else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return userQuestionResultVO;
    }
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        Long questionId = submitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        } else {
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID, Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(), questionES.getMainFuc()));
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }
    //这里是将用户代码和mainfuc进行一个拼接
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            //最后的一个截断是将targetCharacter拼接上去，左闭右开
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceImplException(ResultCode.FAILED);
    }
}
